import React from "react";
import Button from '@iso/components/uielements/button';
import {UploadOutlined} from "@ant-design/icons";
import {showErrorMessage} from "@iso/containers/Feedback/Message/MessageUtils";


export default  class FileUploadButton extends React.Component {

    state = {

    };

    contains=(val,array:any)=> {
        for (let i = 0; i < array.length; i++) {
            if (array[i] == val) {
                return true;
            }
        }
        return false;
    };



    render() {

        let buttonId=this.props.config.id;

        return (

            <>
                <Button
                    key="submit"
                    type="primary"
                    size="small"
                    icon={<UploadOutlined/>}
                    onClick={() =>{
                    document.getElementById(buttonId).click();

                }}>
                    上传
                </Button>

                <input type={"file"} id={buttonId} name={"fileUpload"} style={{display: "none"}} onChange={()=>{
                    let files=document.querySelector('input[type=file]').files;
                    let accept= this.props.config.accept;
                    for(let i=0;i<files.length;i++){
                        let file=files[i];
                        let filename=file.name;
                        //文件类型
                        let type = filename.substring(filename.lastIndexOf(".") );
                        if(!this.contains(type,accept)){
                            showErrorMessage('请选择:'+accept.join(",")+"格式的文件!");
                            return;
                        }
                        if (window.FileReader){
                            let reader = new FileReader();
                            reader.readAsDataURL(file);
                            //监听文件读取结束后事件
                            reader.onloadend = (e)=> {
                                let fileContentArray=new Array();
                                let fileContent={"content":e.target.result,"name":filename,"contentType":file.type,"size":file.size};
                                fileContentArray.push(fileContent);
                                this.props.onChange(fileContentArray);
                                document.getElementById(buttonId).value="";
                            };
                        }
                    }



                }} />

            </>
        );
    }
}

FileUploadButton.defaultProps={
    config:{accept: []},
    onChange:(fileContentArray:Array)=>{}
};
